<template>
  <div style="margin-bottom: 20px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item prop="matterName" label="事项名称:">
        <el-input
            v-model="queryParams.matterName"
            placeholder="事项名称"
            clearable
            @keyup.enter.native="handleQuery"
            suffix-icon="search"
            :suffix-icon-click="handleQuery"
        />
      </el-form-item>


      <el-form-item prop="matterResponsibleId" label="负责人:">
        <el-select filterable v-model="queryParams.matterResponsibleId" placeholder="请选择"
                   clearable style="width: 180px" @focus="fetchRelatedPolicies">
          <el-option v-for="item in user"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="isTimeOut" label="是否超期:">
        <el-select v-model="queryParams.isTimeOut" placeholder="请选择" clearable style="width: 180px">
          <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item prop="isKeyWork" label="是否重要工作:" label-width="100px">
        <el-select v-model="queryParams.isKeyWork" placeholder="请选择" clearable style="width: 180px">
          <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="em1" label="状态:">
        <el-select v-model="queryParams.em1" placeholder="请选择" clearable style="width: 180px">
          <el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <ElLine :title="'事项清单'"/>
    <el-table v-loading="loading" :data="matterList" @selection-change="handleSelectionChange">
<!--      <el-table-column width="50px" type="selection" align="center"/>-->
      <el-table-column min-width="15%" label="事项名称" align="center" prop="matterName"/>

      <el-table-column min-width="5%" label="负责人" align="center" prop="matterResponsible"/>
      <el-table-column min-width="5%" label="协同人" align="center" prop="collaborators"/>
      <el-table-column min-width="7%" label="计划完成时间" align="center" prop="completionDeadline"/>
      <el-table-column min-width="5%" label="超期天数" align="center">
        <template #default="scope">
          <span class="overdue-days">{{ scope.row.cqts }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="5%" label="状态" align="center">
        <template #default="scope">
        <span :style="{ color: getStatusColor(scope.row) }">
          {{ getStatusText(scope.row) }}
        </span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" label="催办意见" align="center" prop="dialogContent"/>
      <el-table-column min-width="5%" label="当前进展" align="center" prop="xxx"/>
      <el-table-column min-width="6%" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="mini" type="success" plain @click="getInto(scope.row)">进入</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-show="total > 0"
        :current-page.sync="queryParams.pageNum"
        :page-size.sync="queryParams.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        style="width: 97%; margin-top: 10px;"
        :pager-count="5"
    />

    <el-dialog v-model="dialogFormVisible" title="催办详情" width="70%" center>
      <div style="padding: 0px 50px">


        <el-row style="margin: 30px 0">
          <el-col :span="12" class="info-item">
            <el-row>
              <el-col :span="8" class="info-label">
                <span>事项名称：</span>
              </el-col>
              <el-col :span="14" class="info-value">
                <span class="underline">{{ form.matterName }}</span>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12" class="info-item">
            <el-row>
              <el-col :span="8" class="info-label">
                <span>负责人:</span>
              </el-col>
              <el-col :span="14" class="info-value">
                <span class="underline">{{ form.matterResponsible }}</span>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row style="margin: 30px 0">
          <el-col :span="12" class="info-item">
            <el-row>
              <el-col :span="8" class="info-label">
                <span>协同人：</span>
              </el-col>
              <el-col :span="14" class="info-value">
                <span class="underline">{{ form.collaborators }}</span>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12" class="info-item">
            <el-row>
              <el-col :span="8" class="info-label">
                <span>计划完成时间:</span>
              </el-col>
              <el-col :span="14" class="info-value">
                <span class="underline">{{ form.completionDeadline }}</span>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row style="margin: 30px 0">
          <el-col :span="12" class="info-item">
            <el-row>
              <el-col :span="8" class="info-label">
                <span>超期天数：</span>
              </el-col>
              <el-col :span="14" class="info-value">
                <span class="underline">{{ form.cqts }}</span>
              </el-col>
            </el-row>
          </el-col>

        </el-row>


        <div style="margin-left: -10px">
          <el-row style="margin: 30px 0">
            <el-col :span="4" class="info-label">
              <span>催办意见:</span>
            </el-col>
            <el-col :span="19">
              <el-input  :rows="3"
                         type="textarea" v-model="form.dialogContent" ></el-input>
            </el-col>
          </el-row>
        </div>

      </div>
      <template #footer>
        <div class="dialog-footer  flex-right">
          <el-button type="primary" @click="saveData">
            保存
          </el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>


</template>
<!--催办清单-->
<script>
import {onMounted, reactive, toRefs} from "vue";
import {getUsers} from "@/api/matter/users.js";
import {updteIsKeyWork, dialogList, updateDialog} from "@/api/matter/matter.js";

export default {
  name: "urgeList",
  components: {},

  setup(_, {emit}) {
    const { proxy } = getCurrentInstance();
    // 定义初始状态常量
    const initialMatterInfo = {
      matterList: [],
      loading: false,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '',
        matterResponsibleId: '',
        matterName:'',
        isTimeOut: '',
        isKeyWork: ''
      },
      user: [],// 存储用户选项
      options1: [
        {value: '', label: '全部'},
        {value: '0', label: '重要工作'},
        {value: '1', label: '非重要工作'},
      ],
      options2: [
        {value: '', label: '全部'},
        {value: '0', label: '超期'},
        {value: '1', label: '未超期'},
      ],
      options3: [
        {value: '', label: '全部'},
        {value: '0', label: '进行中'},
        {value: '1', label: '已完成'},
        {value: '2', label: '已终止'},
      ],
      form: {
        matterName:'',
        matterResponsible:'',
        collaborators:'',
        completionDeadline:'',
        cqts:'',
        dialogContent:'',
      },
      dialogTableVisible: false,
      dialogFormVisible: false,
      formLabelWidth: '200px'

    };
    const data = reactive(
        initialMatterInfo
    )


    // 事项负责人
    const fetchRelatedPolicies = () => {
      return new Promise((resolve, reject) => {
        getUsers().then(response => {
          if (response.code === 200) {
            data.user = response.data;
            resolve(); // 成功获取数据后 resolve
          } else {
            proxy.$modal.msgError(result.msg);
            reject(new Error('Failed to fetch policies')); // 失败时 reject，并传递错误信息
          }
        }).catch(error => {
          console.error('Error fetching policies:', error);
          reject(error); // 捕获任何异常，并将其作为错误对象传递给 reject
        });
      });
    };
    // 是否是重要工作
    const handleSwitchChange2 = (row) => {
      // alert(row.isKeyWork)
      updteIsKeyWork({matterId: row.matterId, isKeyWork: row.isKeyWork}).then((response) => {
        row.isKeyWork = response.data.isKeyWork
      })
    };

    const getStatusText = (row) => {
      if (row.em1) {
        return row.em1;
      } else {
        const currentDate = new Date();
        const deadlineDate = new Date(row.completionDeadline);
        return currentDate > deadlineDate ? '超时' : '进行中';
      }
    };
    const handleQuery = () => {
      data.queryParams.pageNum = 1;
      getList();
    };

    const handleCurrentChange = (currentPage) => {
      data.queryParams.pageNum = currentPage;
      getList();
    };
    const getList = () => {
      data.loading = true;

      dialogList(data.queryParams)
          .then(response => {
            // 处理返回的数据
            data.matterList = response.data.list.map(item => {
              const currentDate = new Date();
              const deadlineDate = new Date(item.completionDeadline);
              const actualCompletionDate = item.summaryDate ? new Date(item.summaryDate) : null;

              let daysDiff = '';
              if (actualCompletionDate) {
                // 计算实际完成时间和计划完成时间的超期天数
                const timeDiff = actualCompletionDate - deadlineDate;
                daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
                daysDiff = daysDiff > 0 ? daysDiff : 0; // 超期天数小于0时设为0
              } else {
                // 计算计划完成时间和当前时间的超期天数
                const timeDiff = currentDate - deadlineDate;
                daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
                daysDiff = daysDiff > 0 ? daysDiff : ''; // 超期天数小于0时设为空字符串
              }

              return {
                ...item,
                cqts: daysDiff
              };
            });
            data.total = response.data.total;
          })
          .catch(error => {
            console.error('API request error:', error);
          })
          .finally(() => {
            data.loading = false;
          });
    };

    onMounted(() => {
      getList();
    });
    const handleSelectionChange = (selection) => {
      data.ids = selection.map((item) => item.matterId);
      data.single = selection.length !== 1;
      data.multiple = !selection.length;
    };
    const getStatusColor = (row) => {
      if (row.em1) {
        return 'black';
      } else {
        const currentDate = new Date();
        const deadlineDate = new Date(row.completionDeadline);
        return currentDate > deadlineDate ? 'red' : 'blue';
      }
    };

    const saveData = () => {

      updateDialog(data.form).then(res=>{
        proxy.$modal.msgSuccess("保存成功");
        // 保存完成后关闭对话框
        data.dialogFormVisible = false;
        getList();
      })


    };

    const getInto = (row) => {
      data.form.dialogId = row.dialogId
      data.form.matterName = row.matterName
      data.form.matterResponsible = row.matterResponsible
      data.form.collaborators = row.collaborators
      data.form.completionDeadline = row.completionDeadline
      data.form.cqts = row.cqts
      data.form.dialogContent = row.dialogContent
      data.dialogFormVisible = true
    };

    const resetQuery = () => {
      Object.assign(data.queryParams, {
        pageNum: 1,
        pageSize: 10,
        keyWord: '',
        matterResponsibleId: '',
        matterName:'',
        isTimeOut: '',
        isKeyWork: ''
      });
      handleQuery();
    };

    return {
      ...toRefs(data),
      handleQuery,
      fetchRelatedPolicies,
      handleSwitchChange2,
      getStatusText,
      getList,
      handleCurrentChange,
      handleSelectionChange,
      getStatusColor,
      getInto,
      saveData,
      resetQuery
    }
  }
}
</script>

<style scoped>
.overdue-days {
  color: red;
}

.info-item {
  font-size: 16px; /* 设置字体大小 */
}

.info-label {
  margin-right: 10px;
  text-align: right;
  font-size: 18px; /* 设置标签字体大小 */
}

.info-value {
  flex-grow: 1;
  text-align: left; /* 确保文本左对齐 */
  position: relative;
}

.info-value .underline::after {
  content: '';
  display: block;
  width: 100%; /* 固定下划线长度，可以根据需要调整 */
  height: 1px;
  background-color: #ccc; /* 调整下划线颜色 */
  position: absolute;
  bottom: -2px;
  left: 0;
}

.flex-right {
  display: flex;
  justify-content: flex-end;
}

</style>
